<template>
  <div class="page-container">
    <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
    <DynamicTable :tables="dyTable" :config="dyTableConfig" ref="directoryRef" :icons="dyIcons"> </DynamicTable>
  </div>
  <HistoryDetail v-model:visible="state.showDetail" :data="data" v-if="state.showDetail" />
</template>

<script lang="ts" setup>
import { getCurrentInstance, onBeforeUnmount, reactive, ref } from 'vue';
import { Api, advancedQueryPreview } from '@/config/api/fileQuery';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { DYNAMICLOCALTABLE } from '@/mixins/subject/subject-types';
import { filter } from 'rxjs/operators';
import { HOST } from '@/config';
import { message } from 'ant-design-vue';
import { useUserStoreWithOut } from '@/store/modules/user';
import HistoryDetail from './components/historyDetail.vue';
import indexService from './index.service';

const accessToken = useUserStoreWithOut().getToken;
const data = ref<Object>({});
const state = reactive({
  searchName: '',
  showDetail: false,
  selectedKeys: [],
  showTree: true,
  treeData: []
});
const directoryRef = ref(null);
const { proxy }: any = getCurrentInstance();
const dyConfig: any = {
  labelCol: 6,
  wrapperCol: 18,
  grid: 8, // 分栏
  style: 'table-form',
  cancelSave: true, // 隐藏底部按钮
  combinationMethod(msg) {
    dyTableConfig.queryUrl = Api.advancedQueryPage;
    dyTableConfig.params = { ...msg };
    directoryRef.value.getData();
  }
};
const dyTableConfig: any = {
  queryUrl: Api.advancedQueryPage,
  protType: 'post',
  isScreen: true,
  isPagingLocalData: true,
  rowClass: {
    showKey: [{ key: 'status', value: 3 }],
    className: 'selected-row-f5'
  },
  rowSelection: {
    type: 'checkbox',
    getCheckboxProps: (record) => ({
      disabled: !record.couldDownload
    })
  }
};

const dyQuestions: any = reactive(indexService.getQuestions());
const dyTable: any = reactive(indexService.getTables());
const dyIcons: any = reactive(indexService.getIcons());
const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    console.log('subscribe item1', item);
    if (item.key === DYNAMICLOCALTABLE && item.value.part.state.name === 'preview') {
      advancedQueryPreview(item.value.data.id, {}).then((res) => {
        if (res && res.success) {
          window.open(res.data);
        }
      });
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '下载') {
      const url = `${Api.advancedQueryDownload}/${item.value.data.id}`;
      downloadFile(url);
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '历史版本') {
      state.showDetail = true;
      data.value = item.value.data;
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '下载') {
      // 所有分页选中数据全部下载 第二页数据初始不选的情况
      if (!directoryRef.value.pagingLocalData[directoryRef.value.pagination.pageNumber]) {
        return message.warning('请先选中一个选项');
      }
      // 所有分页选中当中都没有当前分页的选中数据
      const result = directoryRef.value.dataList.value.some((obj) => {
        for (let item of directoryRef.value.pagingLocalData[directoryRef.value.pagination.pageNumber]) {
          return item.id !== obj.id;
        }
      });
      if (!result && directoryRef.value.pagingLocalData.length !== 0) {
        message.warning('请先选中一个选项');
        return;
      }
      // 所有分页选中数据全部下载
      let idArr: Array<String> = []; // id多选
      for (let key in directoryRef.value.pagingLocalData) {
        for (let obj of directoryRef.value.pagingLocalData[key]) {
          idArr.push(obj.id);
        }
      }
      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${HOST}${Api.advancedQueryBatchDownload}`, true);
      xhr.setRequestHeader('token', accessToken);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.responseType = 'blob';
      xhr.onload = function () {
        if (this.status == 200) {
          const blob = new Blob([this.response], { type: 'contentType' });
          const contentDisposition = xhr.getResponseHeader('content-disposition');
          let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
          filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
          const a = document.createElement('a');
          a.href = window.URL.createObjectURL(blob);
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(Api.advancedQueryBatchDownload);
        }
      };
      xhr.send(JSON.stringify({ ids: idArr }));
      // if (item.state.selected.length) {
      //   let idArr: Array<String> = []; // id多选
      //   for (let i of item.state.selected) {
      //     idArr.push(i.id);
      //   }

      //   const xhr = new XMLHttpRequest();
      //   xhr.open('POST', `${HOST}${Api.advancedQueryBatchDownload}`, true);
      //   xhr.setRequestHeader('token', accessToken);
      //   xhr.setRequestHeader('Content-Type', 'application/json');
      //   xhr.responseType = 'blob';
      //   xhr.onload = function () {
      //     if (this.status == 200) {
      //       const blob = new Blob([this.response], { type: 'contentType' });
      //       const contentDisposition = xhr.getResponseHeader('content-disposition');
      //       let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      //       filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      //       const a = document.createElement('a');
      //       a.href = window.URL.createObjectURL(blob);
      //       a.download = filename;
      //       a.click();
      //       window.URL.revokeObjectURL(Api.advancedQueryBatchDownload);
      //     }
      //   };
      //   xhr.send(JSON.stringify({ ids: idArr }));
      // } else {
      //   message.warn('请先选中行');
      // }
    }
  });
// 输入搜索
// function handleChange() {}
// function handleNodeSelect(_: any, { node }) {
//   const params = {
//     id: node.id
//   };
//   directoryRef.value.getData(params);
// }

// 下载文件
const downloadFile = (url) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
};

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }
  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;
    &.ant-tree-node-selected {
      color: #005aea;
      background: #e5eefd;
      border-radius: 6px;
    }
  }
}
:deep(.ant-table-cell-fix-right) {
  background: transparent;
}
.hide-text {
  width: 35px;
  padding-top: 7px;
  text-align: center;
}
.p-4 {
  padding: 2rem 2rem 1rem 1rem;
}
.tree-icon {
  text-align: right;
  position: relative;
  .anticon-left {
    position: absolute;
    right: -25px;
    top: -25px;
  }
}
</style>
